import 'whatwg-fetch'
import 'es6-promise/dist/es6-promise.min.js'
import 'fetch-ie8/fetch.js'
import jquery from 'jquery'
import loginSession from './localSession'
import config from './config'

const { api } = config
const { targetHost } = api

const { ajax } = jquery
/**
 * 异步请求
 * */
export default (function () {
  function fetchRequest (url, method, param, isValid, isUpload) {
    if (url.indexOf('http://') !== 0) {
      url = targetHost + url
    }
    const options = {}
    if (method === 'post') {
      options.method = 'post'
    } else {
      options.method = 'get'
    }
    const headers = {}
    if (!isUpload) {
      headers['Content-type'] = 'application/json;charset=UTF-8'
      if (param) {
        options.body = JSON.stringify(param)
      }
    } else {
      options.body = param
    }

    if (isValid) {
      headers.token = loginSession.getToken()
    }
    options.headers = headers
    const result = {
      success: true,
      data: undefined,
      errorMsg: undefined }
    return fetch(url, options)
      .then((res) => {
        return res.json()
      })
      .then((data) => {
        if (data.flag) {
          result.data = data.data
          return result
        }
        if (data.code === 'er_000001') {
          window.location.href = `${window.location.origin}/login`
        }
        result.success = false
        result.errorMsg = data.message
        return result
      })
      .catch(() => {
        result.success = false
        result.errorMsg = '服务器异常'
        return result
      })
  }
  return {
    post (url, param) {
      return fetchRequest(url, 'post', param, true)
    },
    get (url) {
      return fetchRequest(url, 'get', undefined, true)
    },
    postNoValid (url, param) {
      return fetchRequest(url, 'post', param, false)
    },
    getNoValid (url) {
      return fetchRequest(url, 'get', undefined, false)
    },
    upload (url, param) {
      return fetchRequest(url, 'post', param, true, true)
    },
    ajax (url, options = { type: 'get' }) {
      return ajax(url, options).then((data) => {
        return data
      })
    },
  }
}())
